package com.cdshop.web.auth;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cdshop.web.NavigatorService;

public class AuthenticateFilter implements Filter {

	public static final String INIT_PARAM_FORWARD = "forward";

	private String forward;

	@Override
	public void init(FilterConfig config) throws ServletException {
		forward = config.getInitParameter(INIT_PARAM_FORWARD);
		if (forward == null) {
			forward = "/";
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreqs = (HttpServletRequest) request;
		HttpServletResponse hresp = (HttpServletResponse) response;
		HttpSession session = hreqs.getSession();
		if (!AuthenticateService.instance().isLoggedIn(session)) {
			NavigatorService nav = NavigatorService.instance();
			nav.setCaptureURL(hreqs);
			nav.forward(hreqs, hresp, forward);
			return;
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// nothing
	}
}
